package persistence.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * 
 * @author paul jaklitsch
 * 
 * Implementation of <code>ConnectionProvider</code>, getting connections
 * from a connection pool provided by tomcat
 *
 */
public class ProductionConnectionProvider implements ConnectionProvider{
	
	private DataSource dataSource;
	
	public Connection getConnection() {
		/* code partially taken from 
		 * http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html#PostgreSQL
		 */	
		Connection con=null;
		try {
			if (dataSource == null) {
				InitialContext cxt = new InitialContext();
				dataSource = (DataSource) cxt.lookup("java:/comp/env/jdbc/postgres");
			}
			con=dataSource.getConnection();
		}
		catch (NamingException ne) {
			System.out.println(ne.getMessage());
			//TODO: use TestConnectionProvider as fallback
		}
		catch (SQLException se) {
			System.out.println("----------------- SQLException: " + se.getMessage());
			//TODO: handle
		}
		return con;
	}
}